package logic

import (
	"context"
	"fmt"
	"huiyun/model/cache"
	"math/rand"
	"time"

	"huiyun/huiyunrpc/huiyunrpc"
	"huiyun/huiyunrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信发送
func (l *SendSmsLogic) SendSms(in *huiyunrpc.SendSmsRequest) (*huiyunrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	get, _ := cache.Rdb.Get(l.ctx, "senSmsNumber"+in.Phone).Result()
	if get >= "1" {
		return nil, fmt.Errorf("该短信已发送过一次,请稍后再发")
	}
	code := rand.Intn(9000) + 1000
	//sms, _ := pkg.SendSms(in.Phone, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}
	cache.Rdb.Set(l.ctx, "senSms"+in.Phone, code, time.Minute*3)

	incr := cache.Rdb.Incr(l.ctx, "senSmsNumber"+in.Phone)
	if incr.Val() == 1 {
		cache.Rdb.Expire(l.ctx, "senSmsNumber"+in.Phone, time.Minute*1)
	}
	return &huiyunrpc.SendSmsResponse{}, nil
}
